<template>
  <XnDialog custom-class="edit-object-dialog" title="编辑用户信息" :visible.sync="selfVisible" @close="closeDialog">
    <el-scrollbar class="object-form-con">
      <el-form :model="formData" label-width="100px" :rules="rules" ref="objectForm">
        <el-row>
          <el-col :span="8">
            <el-form-item label="姓名：" prop="userName">{{ formData.userName }}</el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="性别：">{{ formData.gender }}</el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="职位：" prop="post">{{ formData.post }}</el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="8">
            <el-form-item label="所属机构：" prop="userOrgId">
              <el-select
                v-model="formData.userOrgId"
                placeholder="请选择所属机构"
                size="small"
                @change="onChangeDiaOrg">
                <el-option
                  v-for="item in orgList"
                  :key="item.orgId"
                  :label="item.orgName"
                  :value="item.orgId"></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="上级领导：" prop="userLeaderName">
              <el-input size="small" disabled v-model="formData.userLeaderName" style="width: 2rem"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="政治面貌：">{{ formData.politics }}</el-form-item>
          </el-col>
        </el-row>
        <el-form-item label="用户身份：" prop="userIdentity">
          <el-radio-group v-model="formData.userIdentity" disabled>
            <el-radio :label="item.code" v-for="item in userIdentity" :key="item.code">
              {{ item.name }}
            </el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="用户状态：" prop="userStatus">
          <el-radio-group v-model="formData.userStatus" disabled>
            <el-radio :label="item.code" v-for="item in userStatus" :key="item.code">
              {{ item.name }}
            </el-radio>
          </el-radio-group>
        </el-form-item>
        <el-row>
          <el-col :span="12" class="col-date">
            <el-form-item label="日期标注：">
              <el-checkbox-group v-model="checkList">
                <el-checkbox :label="item.labelCode" v-for="item in labelList" :key="item.labelCode">
                  <div @click.stop="onClick($event)">
                    <el-form-item :label="item.labelName + '日期：'">
                      <el-date-picker
                        v-model="item.labelValue"
                        type="date"
                        placeholder="选择日期"
                        size="small"
                        format="yyyy-MM-dd"
                        value-format="yyyy-MM-dd"></el-date-picker>
                    </el-form-item>
                  </div>
                </el-checkbox>
              </el-checkbox-group>
              <span class="tip">提示：日期标注勾选后可在列表中展示</span>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="考核状态：" prop="status">
              <el-radio-group v-model="formData.status" class="remark-radio" @change="statusChange('status')">
                <el-radio label="0">参与考核、定等次（正常考评）</el-radio>
                <el-radio label="2">直接定等次（参评占全局基数、不发处室）</el-radio>
                <el-radio label="1">不参与考核</el-radio>
              </el-radio-group>
            </el-form-item>
            <el-form-item
              label="等次结果："
              prop="defaultRank"
              :rules="formData.status === '2' ? rules.defaultRank : []"
              v-if="formData.status === '2'">
              <el-radio-group
                v-model="formData.defaultRank"
                class="status-radio"
                :disabled="formData.status !== '2'"
                @change="statusChange('result')">
                <el-radio :label="item.code" v-for="item in resultList" :key="item.code">
                  {{ item.name }}
                </el-radio>
              </el-radio-group>
            </el-form-item>
            <el-form-item
              label="原因："
              prop="reason"
              :rules="ressonShow ? rules.reason : []"
              v-if="ressonShow"
              class="reason">
              <el-radio-group v-model="formData.reason" class="remark-radio" :disabled="!ressonShow">
                <el-radio :label="item.id" v-for="item in remarkList" :key="item.id">
                  {{ item.text }}
                  <el-input
                    v-model="formData.reasonWord"
                    size="mini"
                    v-if="item.text === '其他'"
                    maxlength="30"></el-input>
                </el-radio>
              </el-radio-group>
            </el-form-item>
          </el-col>
        </el-row>
        <el-form-item label="备注：">
          <el-input
            v-model="formData.remark"
            type="textarea"
            maxlength="50"
            :autosize="{ minRows: 3, maxRows: 5 }"></el-input>
        </el-form-item>
        <el-row>
          <el-col :span="12">
            <el-form-item label="修改时间：">{{ formData.editTime }}</el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="修改人：">{{ formData.editName }}</el-form-item>
          </el-col>
        </el-row>
      </el-form>
    </el-scrollbar>
    <div class="btn-box">
      <el-button size="small" @click.stop="closeDialog">取消</el-button>
      <el-button size="small" type="primary" @click.stop="onFormSave">确定</el-button>
    </div>
  </XnDialog>
</template>
<script>
// import { cloneDeep } from 'lodash'
import XnDialog from '@com/xnDialog.vue'
import { formatDate } from '@utility/utility'
import { getAssessUserDetail, getlistOrgAndLeader } from '@api/modules/assessManage.js'
import { saveAssessUser } from '@apis/grade.js'
import { cloneDeep } from 'lodash'

export default {
  name: 'AccountDialog',
  components: { XnDialog },
  emits: ['close', 'submit'],
  props: {
    visible: {
      type: Boolean,
      default: false,
    },
    userData: {
      type: Object,
      default: () => {},
    },
    userStatus: {
      type: Array,
      default: () => [],
    },
    userIdentity: {
      type: Array,
      default: () => [],
    },
  },
  data() {
    return {
      formData: {
        id: '',
        userId: '',
        userName: '', // 用户姓名
        gender: '', // 用户性别
        post: '', // 用户职位
        userOrgId: '', // 用户机构
        userOrgName: '', // 用户机构
        userLeaderId: '', // 用户领导
        userLeaderName: '', // 用户领导
        politics: '', // 用户政治面貌
        userIdentity: '', // 用户身份
        userStatus: '', // 用户状态
        status: '1', // 用户考核状态
        reason: '', // 用户考核原因
        reasonWord: '', // 用户考核原因其他备注
        entryDate: '', // 用户入职日期
        retireDate: '', // 用户退休日期
        transferDate: '', // 用户调岗日期
        expatriateDate: '', // 用户外拍日期
        departDate: '', // 用户离职日期
        remark: '', // 用户备注
        defaultRank: '', // 用户等次结果
        editTime: '',
        editName: JSON.parse(localStorage.getItem('PSKH_USERINFO')).userName,
      },
      remarkList: [
        {
          id: '0',
          text: '新录用公务员在试用期内的；',
        },
        {
          id: '1',
          text: '病、事假累计时间超过当期平时考核周期一半的；',
        },
        {
          id: '2',
          text: '涉嫌违法违纪被立案调查尚未结案的；',
        },
        {
          id: '3',
          text: '法律、法规规定的其他情形。',
        },
        {
          id: '4',
          text: '其他',
        },
      ],
      // userIdentity: [],
      // userStatus: [],

      rules: {
        userName: [{ required: true, message: '请选择用户姓名', trigger: 'change' }],
        post: [{ required: true, message: '请选择用户职位', trigger: 'change' }],
        userOrgId: [{ required: true, message: '请选择所属机构', trigger: 'change' }],
        userLeaderName: [{ required: true, message: '请选择上级领导', trigger: 'change' }],
        userIdentity: [{ required: true, message: '请选择用户身份', trigger: 'change' }],
        userStatus: [{ required: true, message: '请选择用户状态', trigger: 'change' }],
        status: [{ required: true, message: '请选择考核状态', trigger: 'change' }],
        reason: [{ required: true, message: '请选择相关原因', trigger: 'change' }],
        defaultRank: [{ required: true, message: '请选择等次结果', trigger: 'change' }],
      },
      orgList: [],
      resultList: [
        { name: '好', code: '1' },
        { name: '较好', code: '2' },
        { name: '一般', code: '3' },
        { name: '较差', code: '4' },
        { name: '不定等次', code: '6' },
      ],
      selfVisible: false,
      labelList: [
        {
          labelCode: 'ENTRY',
          labelName: '入职',
          labelValue: '',
          labelShow: '0',
          id: '',
        },
        {
          labelCode: 'RETIRE',
          labelName: '退休',
          labelValue: '',
          labelShow: '0',
          id: '',
        },
        {
          labelCode: 'TRANSFER_POSITION',
          labelName: '调岗',
          labelValue: '',
          labelShow: '0',
          id: '',
        },
        {
          labelCode: 'EXPATRIATE',
          labelName: '外派',
          labelValue: '',
          labelShow: '0',
          id: '',
        },
        {
          labelCode: 'DEPART',
          labelName: '离职',
          labelValue: '',
          labelShow: '0',
          id: '',
        },
      ],
      checkList: [], // 用户日期标注选择
    }
  },
  filters: {
    filterDate(val) {
      if (val) {
        return formatDate(new Date(val).toLocaleString(), 'yyyy-MM-dd hh:mm:ss')
      }
      return '-'
    },
  },
  watch: {
    visible(bool) {
      this.selfVisible = bool
    },
    userData: {
      handler(news) {
        if (news.userId) {
          this.dealData(news)
          this.getDetail(news.id)
          this.getOrg(news.userId)
        }
      },
      deep: true,
      immediate: true,
    },
  },
  computed: {
    ressonShow() {
      if (this.formData.status === '1' || (this.formData.status === '2' && this.formData.defaultRank === '6')) {
        return true
      } else {
        return false
      }
    },
  },
  created() {},
  methods: {
    closeDialog() {
      this.$refs.objectForm && this.$refs.objectForm.resetFields()
      this.formData = {
        id: '',
        userId: '',
        userName: '', // 用户姓名
        gender: '', // 用户性别
        post: '', // 用户职位
        userOrgId: '', // 用户机构
        userOrgName: '', // 用户机构
        userLeaderId: '', // 用户领导
        userLeaderName: '', // 用户领导
        politics: '', // 用户政治面貌
        userIdentity: '', // 用户身份
        userStatus: '', // 用户状态
        status: '1', // 用户考核状态
        reason: '', // 用户考核原因
        reasonWord: '', // 用户考核原因其他备注
        entryDate: '', // 用户入职日期
        retireDate: '', // 用户退休日期
        transferDate: '', // 用户调岗日期
        expatriateDate: '', // 用户外拍日期
        departDate: '', // 用户离职日期
        remark: '', // 用户备注
        defaultRank: '', // 用户等次结果
        editTime: '',
        editName: JSON.parse(localStorage.getItem('PSKH_USERINFO')).userName,
      }
      this.selfVisible = false
      this.$emit('close', false)
      this.$emit('update:visible', false)
    },
    onFormSave() {
      this.$refs.objectForm.validate(valid => {
        if (valid) {
          this.submitSave()
        }
      })
    },
    getDetail(id) {
      getAssessUserDetail(id).then(res => {
        this.formData.remark = res.data.remark || ''
        this.formData.userOrgId = res.data.orgId
        this.formData.userOrgName = res.data.orgName
        this.formData.userLeaderId = res.data.leaderId
        this.formData.userLeaderName = res.data.leaderName
        this.formData.defaultRank = res.data.defaultRank
      })
    },
    getOrg(id) {
      getlistOrgAndLeader(id).then(res => {
        this.orgList = res.data
      })
    },
    dealData(data) {
      const { userInfo } = data
      this.formData.editTime = formatDate(new Date().toLocaleString(), 'yyyy-MM-dd')
      this.formData.userName = userInfo.userName
      this.formData.gender = userInfo.gender
      this.formData.post = userInfo.post
      this.formData.politics = userInfo.politics
      this.formData.userIdentity = userInfo.userIdentity
      this.formData.userStatus = String(userInfo.userStatus)
      this.formData.status = data.status
      this.formData.id = data.id
      this.formData.userId = data.userId
      if (data.status === '1' || (data.status === '2' && data.defaultRank === '6')) {
        if (data.reason.length === 1) {
          this.formData.reason = data.reason
        } else {
          this.formData.reason = '4'
          this.formData.reasonWord = data.reason.slice(1)
        }
      }
      if (data.labelList.length) {
        this.labelList = cloneDeep(data.labelList)
        data.labelList.forEach(item => {
          if (item.labelShow === '1') {
            this.checkList.push(item.labelCode)
          }
        })
      } else {
        this.labelList.forEach(item => {
          item.labelShow = '0'
          item.labelValue = ''
          item.id = ''
        })
        this.checkList = []
      }
    },
    onChangeDiaOrg() {
      const arr = this.orgList.filter(item => {
        return item.orgId === this.formData.userOrgId
      })
      this.formData.userOrgName = arr[0].orgName
      this.formData.userLeaderId = arr[0].mainLeaderList[0].userId
      this.formData.userLeaderName = arr[0].mainLeaderList[0].userName
    },
    statusChange(type) {
      if (this.formData.defaultRank && type === 'status') {
        this.formData.defaultRank = ''
      }
      if (this.formData.reason) {
        this.formData.reason = ''
      }
      if (this.formData.reasonWord) {
        this.formData.reasonWord = ''
      }
    },
    submitSave() {
      if (this.formData.status === '1' && !this.formData.reason) {
        this.$message.warning('请选择不参与考核原因')
        return false
      }
      if (this.formData.status === '2' && !this.formData.defaultRank) {
        this.$message.warning('请选择等次结果')
        return false
      }
      if (this.formData.status === '2' && this.formData.defaultRank === '6' && !this.formData.reason) {
        this.$message.warning('请选择不定等次原因')
        return false
      }
      if (this.formData.reason === '4' && !this.formData.reasonWord.trim().length) {
        this.$message.warning('请填写具体的原因')
        return false
      }
      let reason = this.formData.reason
      if (this.formData.reason === '4') {
        reason = '4' + this.formData.reasonWord
      }
      this.labelList.forEach(item => {
        item.labelValue = item.labelValue || ''
        if (this.checkList.includes(item.labelCode)) {
          item.labelShow = '1'
        } else {
          item.labelShow = '0'
        }
      })

      const param = {
        status: this.formData.status,
        reason: reason,
        remark: this.formData.remark,
        leaderId: this.formData.userLeaderId,
        leaderName: this.formData.userLeaderName,
        orgId: this.formData.userOrgId,
        orgName: this.formData.userOrgName,
        id: this.formData.id,
        userId: this.formData.userId,
        defaultRank: this.formData.defaultRank,
        labelList: this.labelList,
      }
      saveAssessUser(param).then(res => {
        if (res.status === 200) {
          this.$message.success('填报成功')
          this.editDialogShow = false
          this.$emit('submit')
          this.closeDialog()
        }
      })
    },
    onClick(e) {
      e.preventDefault()
    },
  },
}
</script>
<style lang="scss" scoped>
.edit-object-dialog {
  ::v-deep &.el-dialog {
    // margin-top: 5vh !important;
    width: 70%;
    height: 65vh;
    max-height: 1200px;
    min-width: 640px;
    max-width: 1100px;

    .object-form-con {
      height: calc(100% - 60px);
      display: flex;
      flex-direction: column;
    }

    .el-form {
      flex: 1;
      padding: 0 20px;

      .el-input,
      .el-select {
        width: auto;
      }
    }
    .status-radio {
      .el-radio {
        margin-right: 10px;
      }
    }
    .remark-radio {
      .el-radio {
        width: 95%;
        margin-top: 5px;
        line-height: 25px;
      }
      .el-input {
        width: 70%;
      }
    }
    .col-date {
      border-right: 1px solid #d2d2d2;
      margin-bottom: 10px;
      .tip {
        color: #999999;
      }
      .el-input {
        width: 80%;
      }
    }

    .btn-box {
      text-align: right;
      border-top: 1px solid #dedede;
      padding-top: 20px;
    }
  }
}
</style>
